package org.ewaf.framework.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang.StringUtils;

public class ParamUtil {

	private static final String DATA_ENCODING = "UTF-8";

	public static Map<String, String> str2map(String str) {
		if (StringUtils.isBlank(str)) {
			return null;
		}

		Map<String, String> map = new HashMap<String, String>();

		String[] items = str.split("&");
		for (String item : items) {
			int offset = item.indexOf('=');
			if (offset > 0) {
				String key = item.substring(0, offset);
				String value = item.substring(offset + 1);

				if (StringUtils.isNotBlank(key)
						&& StringUtils.isNotBlank(value)) {
					try {
						key = URLDecoder.decode(key, DATA_ENCODING);
						value = URLDecoder.decode(value, DATA_ENCODING);
						map.put(key, value);
					} catch (UnsupportedEncodingException ex) {
						throw new RuntimeException(ex);
					}
				}
			}
		}

		return map;
	}

	public static String map2Str(Map<String, String> map) {
		if (map == null) {
			return null;
		}

		StringBuffer sb = new StringBuffer();

		for (Entry<String, String> e : map.entrySet()) {
			String key = e.getKey();
			String value = e.getValue();

			if (StringUtils.isNotBlank(key) && StringUtils.isNotBlank(value)) {
				if (sb.length() > 0) {
					sb.append('&');
				}

				try {
					sb.append(URLEncoder.encode(key, DATA_ENCODING));
					sb.append('=');
					sb.append(URLEncoder.encode(value, DATA_ENCODING));
				} catch (UnsupportedEncodingException ex) {
					throw new RuntimeException(ex);
				}
			}
		}

		return sb.toString();
	}

	public static String list2Str(List<Integer> list) {

		if (list == null) {

			return "";
		}

		if(list.size()==0){
			
			return "";
		}
		
		StringBuffer sb = new StringBuffer();

		for (Integer i : list) {

			sb.append(i + "&");

		}		
		String s = sb.toString().substring(0, sb.toString().lastIndexOf('&'));

		return s;
	}

	public static List<Integer> str2List(String str) {

		if (StringUtils.isBlank(str)) {

			return null;
		}

		String[] items = str.split("&");
		List<Integer> list = new ArrayList<Integer>();
		for (String s : items) {

			list.add(Integer.valueOf(s));

		}

		return list;

	}	
}
